/**
 *
 */
package com.pocketsweet.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.pocketsweet.MLApplication;
import com.pocketsweet.R;
import com.pocketsweet.ui.SignInRecord;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.ToastEx;

import org.ocpsoft.prettytime.PrettyTime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author bobhu 工具集合
 */
public class ToolKits {

    public static PrettyTime prettyTime = new PrettyTime();
    public static final String[] starArr = {"水瓶座", "双鱼座", "牡羊座", "金牛座", "双子座",
            "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "魔羯座"};
    public static final int[] DayArr = {20, 19, 21, 20, 21, 22, 23, 23, 23,
            24, 23, 22};

    public static String getDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
        return format.format(date);
    }

    public static String millisecs2DateString(long timestamp) {
        long gap = System.currentTimeMillis() - timestamp;
        if (gap < 1000 * 60 * 60 * 24) {
            return prettyTime.format(new Date(timestamp));
        } else {
            return getDate(new Date(timestamp));
        }
    }

    public static boolean haveTimeGap(long lastTime, long time) {
        int gap = 1000 * 60 * 10;// 10 mins
        return time - lastTime > gap;
    }

    public static String showCommentTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    public static String showTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }

    /**
     * @param Date date
     * @return Age
     */
    public static int countAge(Date date) {
        Date now = new Date(System.currentTimeMillis());
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(now);
        Calendar calendar1 = GregorianCalendar.getInstance();
        calendar1.setTime(date);
        return calendar.get(Calendar.YEAR) - calendar1.get(Calendar.YEAR);
    }

    // 计算多久之前
    public static String getTimeDiff(Date date) {
        Calendar cal = Calendar.getInstance();
        long diff = 0;
        Date dnow = cal.getTime();
        String str = "";
        diff = dnow.getTime() - date.getTime();

        if (diff > 2592000000L) {// 30 * 24 * 60 * 60 * 1000=2592000000 毫秒
            str = "1个月前";
        } else if (diff > 1814400000) {// 21 * 24 * 60 * 60 *
            // 1000=1814400000 毫秒
            str = "3周前";
        } else if (diff > 1209600000) {// 14 * 24 * 60 * 60 *
            // 1000=1209600000 毫秒
            str = "2周前";
        } else if (diff > 604800000) {// 7 * 24 * 60 * 60 * 1000=604800000
            // 毫秒
            str = "1周前";
        } else if (diff > 86400000) { // 24 * 60 * 60 * 1000=86400000 毫秒
            // System.out.println("X天前");
            str = (int) Math.floor(diff / 86400000f) + "天前";
        } else if (diff > 3600000) {// 60 * 60 * 1000=18000000 毫秒
            // System.out.println("X小时前");
            str = (int) Math.floor(diff / 3600000f) + "小时前";
        } else if (diff > 60000) {// 1 * 60 * 1000=60000 毫秒
            // System.out.println("X分钟前");
            str = (int) Math.floor(diff / 60000) + "分钟前";
        } else if (diff >= 0) {
            str = (int) Math.floor(diff / 1000) + "秒前";
        } else {
            str = "1秒前";
        }
        return str;
    }

    // 把分钟换成小时，天
    public static String translateMinToStandard(Long min) {
        String str = "";

        // if (min > 43200) {// 30 * 24 * 60 =43200
        // str = (int) Math.floor(min / 43200) + "个月";
        // } else if (min > 30240) {// 21 * 24 * 60
        // // 1000=1814400000 毫秒
        // str = "3周";
        // } else if (min > 20160) {// 14 * 24 * 60
        // // 1000=1209600000 毫秒
        // str = "2周";
        // } else if (min > 10080) {// 7 * 24 * 60 * 60 * 1000=604800000
        // // 毫秒
        // str = "1周";
        // } else
        if (min >= 1440) { // 24 * 60 * 60 * 1000=86400000 毫秒
            // System.out.println("X天前");
            str = (int) Math.floor(min / 1440) + "天";
            int hour = (int) Math.floor((int) Math.floor(min % 1440) / 60);
            if (hour > 0) {
                str = str + (int) Math.floor((int) Math.floor(min % 1440) / 60)
                        + "小时";
            }
        } else if (min >= 60) {// 60 * 60 * 1000=18000000 毫秒
            // System.out.println("X小时前");
            str = (int) Math.floor(min / 60f) + "小时";
        } else if (min >= 0) {// 1 * 60 * 1000=60000 毫秒
            // System.out.println("X分钟前");
            str = (int) Math.floor(min) + "分钟";
        } else {
            str = "1分钟";
        }
        return str;
    }

    /**
     * @param oldTime 较小的时间
     * @param newTime 较大的时间 (如果为空 默认当前时间 ,表示和当前时间相比)
     * @return -1 ：同一天. 0：昨天 . 1 ：至少是前天.
     * @throws ParseException 转换异常
     * @author LuoB.
     */
    public static int isYeaterday(Date oldTime, Date newTime) {
        if (newTime == null) {
            newTime = new Date();
        }
        // 将下面的 理解成 yyyy-MM-dd 00：00：00 更好理解点
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String todayStr = format.format(newTime);
        Date today;
        try {
            today = format.parse(todayStr);
            // 昨天 86400000=24*60*60*1000 一天
            if ((today.getTime() - oldTime.getTime()) > 0
                    && (today.getTime() - oldTime.getTime()) <= 86400000) {
                return 0;
            } else if ((today.getTime() - oldTime.getTime()) <= 0) { // 至少是今天
                return -1;
            } else { // 至少是前天
                return 1;
            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return -1;

    }

    public static boolean canSignIn(Long time) {
        if (time > 0) {
            Date curDates = new Date(time);// 获取当前时间
            SimpleDateFormat formatters = new SimpleDateFormat("HH:mm");
            String strs = formatters.format(curDates);
            System.out.println(strs);
            // 开始时间
            int startHour = 22;// 小时
            int startMin = 0;// 分
            // 结束时间
            int endHour = 1;// 小时
            int endMin = 0;// 分

            String[] dds = new String[]{};

            // 分取系统时间 小时分
            dds = strs.split(":");
            int curHour = Integer.parseInt(dds[0]);
            int curMin = Integer.parseInt(dds[1]);
//            Log.e("==cur",
//                    "现在是：" + String.valueOf(curHour) + ":" + String.valueOf(curMin));
            if (startHour <= curHour || curHour <= endHour) {
                if (startHour <= curHour || curHour < endHour) {
                    return true;
                    // Log.e("==cur", "现在是：1");
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
        return false;
    }

    /**
     * 计算星座
     *
     * @param Date date
     * @return constellation
     */
    public static String constellation(Date date) {
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        if (day < DayArr[month]) {
            month = month - 1;
        }
        if (month >= 0) {
            return starArr[month];
        }
        return starArr[11];
    }

    // 根据星座名称返回星座的值
    public static int getIndexByConstellatinName(String name) {
        for (int i = 0; i < starArr.length; i++) {
            if (name.equals(starArr[i])) {
                return i;
            }
        }
        return -1;
    }

    /**
     * @param e
     * @return
     */
    public static boolean isEmailFormat(String e) {
        Pattern pattern = Pattern
                .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        Matcher mc = pattern.matcher(e);
        return mc.matches();
    }

    /**
     * @param mobiles
     * @return
     */
    public static boolean isMobileNum(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();

    }

    public static void toast(Context ctx, int id) {
        ToastEx.createToast(ctx, id);
    }

    public static void toastLong(Context ctx, int id) {
        ToastEx.createToast(ctx, id);
    }

    public static void toast(Context context, String str) {
        ToastEx.createToast(context, str);
    }

    // loading dialog

    /**
     * 得到自定义的progressDialog
     *
     * @param context
     * @param msg
     * @return
     */
    public static LoadingDailog createLoadingDialog(Context context, String msg) {
        LoadingDailog loadingDialog = new LoadingDailog(context,
                R.style.LoadingDialog);// 创建自定义样式dialog
        loadingDialog.setText(msg);
        return loadingDialog;
    }

    /**
     * @param contentUri
     * @param activity
     * @return
     */
    public static String getImgRealPathFromURI(Uri contentUri, Activity activity) {
        String sImagePath = getRealPathFromURI(contentUri, activity);
        if (contentUri.getPath().contains("/video/")) {
            Toast.makeText(activity, R.string.video_forbidden,
                    Toast.LENGTH_SHORT).show();
            return null;
        }
        if (sImagePath == null) {
            return contentUri.toString().replace("file://", "");
        } else {
            return sImagePath;
        }
    }

    /**
     * 从系统URI转换到图片对应的在SD卡上的物理地址
     *
     * @param contentUri
     * @return
     */
    private static String getRealPathFromURI(Uri uri, Activity context) {
        // String[] proj = { MediaColumns.DATA };
        // Cursor cursor = activity.managedQuery(contentUri, proj, null, null,
        // null);
        // if (cursor == null)
        // return null;
        //
        // int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        // cursor.moveToFirst();
        // // return cursor.getString(column_index);
        //
        // Cursor cursor = null;
        // try {
        // String[] proj = { MediaStore.Images.Media.DATA };
        // cursor =
        // MLApplication.getContext().getContentResolver().query(contentUri,
        // proj,
        // null, null, null);
        // int column_index = cursor
        // .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        // cursor.moveToFirst();
        // return cursor.getString(column_index);
        // } finally {
        // if (cursor != null) {
        // cursor.close();
        // }
        // }

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;

    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     * <p/>
     * //@param context The context. //@param uri The Uri to query. //@param
     * selection (Optional) Filter used in the query. //@param selectionArgs
     * (Optional) Selection arguments used in the query. //@return The value of
     * the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri,
                                       String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * //@param uri The Uri to check. //@return Whether the Uri authority is
     * ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    /**
     * //@param uri The Uri to check. //@return Whether the Uri authority is
     * DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    /**
     * //@param uri The Uri to check. //@return Whether the Uri authority is
     * MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param context
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {

        final float scale = context.getResources().getDisplayMetrics().density;

        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {

        final float scale = context.getResources().getDisplayMetrics().density;

        return (int) (pxValue / scale + 0.5f);
    }

    public static String generateOrderCode() {
        return getNowDateString() + getRandomNumString(8);
    }

    public static String getNowDateString() {
        Date d = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        return formatter.format(d);
    }

    public static String getRandomNumString(int num) {
        Random r = new Random();
        String tmp = "00000000" + r.nextInt(1000000000);
        return tmp.substring(tmp.length() - num, tmp.length());

    }

    // 截取字符串显示
    public static String subString(String str, int length) {
        if (null != str && str.length() > length) {
            str = str.substring(0, length) + "...";
        }
        return str;
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    // ////////////////////////////////////////////////////
    // dialog
    // ////////////////////////////////////////////////////
    public static ProgressDialog showSpinnerDialog(Activity activity) {
        // activity = modifyDialogContext(activity);

        ProgressDialog dialog = new ProgressDialog(activity);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setCancelable(true);
        dialog.setMessage(MLApplication.getContext()
                .getString(R.string.loading));
        if (activity.isFinishing() == false) {
            dialog.show();
        }
        return dialog;
    }

    public static boolean isSdCardMounted() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    // 获取手机型号
    public static String getPhoneModule() {
        return android.os.Build.MODEL;
    }

    // 获取系统版本
    public static String getSystemType() {
        return android.os.Build.VERSION.RELEASE;
    }

    // 获取当前进程
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /**
     * 得到设备屏幕的宽度
     */
    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 得到设备屏幕的高度
     */
    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 得到设备的密度
     */
    public static float getScreenDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }
}
